import subprocess
import re


print('Miyako ArchLinux Installation Python Scripts.')


def run(command, hide=False) -> int:
    stdout = None
    if hide:
        stdout = subprocess.PIPE
    return subprocess.run(command, shell=True, stdout=stdout).returncode
    # Test
    # print(f"run: {command}")
    # return 0


def pacman_sync() -> int:
    return run('pacman -Sy')


def pacman_inst(*pack_strs) -> int:
    # Collect packs
    packs = []
    for _pack_str in pack_strs:
        packs += _pack_str.split()

    # Check packs
    packs_str = ''
    for pack in packs:
        # search self
        if run(f'pacman -Si {pack}', hide=True) == 0:
            packs_str += (pack + ' ')
        elif run(f'pacman -Sg {pack}', hide=True) == 0:
            packs_str += (pack + ' ')
        # search lib32
        pack = f'lib32-{pack}'
        if run(f'pacman -Si {pack}', hide=True) == 0:
            packs_str += (pack + ' ')

    return run('pacman -S --needed --noconfirm ' + packs_str)


def pacman_inst_from_file(*file_paths) -> int:
    # Complete paths
    paths_str = ''
    for file_path in file_paths:
        paths_str += f'./packs/{file_path}-*.pkg.tar.zst '

    return run(f'pacman -U --needed --noconfirm {paths_str}')


def pacman_remove(*pack_strs) -> int:
    # Collect packs
    packs = []
    for _pack_str in pack_strs:
        packs += _pack_str.split()

    # Check packs
    packs_str = ''
    for pack in packs:
        # search self
        if run(f'pacman -Qi {pack}', hide=True) == 0:
            packs_str += (pack + ' ')
        elif run(f'pacman -Qg {pack}', hide=True) == 0:
            packs_str += (pack + ' ')

    return run('pacman -Runs --noconfirm ' + packs_str)


def is_network_accessible() -> bool:
    return pacman_sync() == 0


def input_yes_or_no(default=True) -> bool:
    opt = input()
    if len(opt) == 0:
        return default
    elif opt.upper().startswith('Y'):
        return True
    else:
        return False


def add_module(*new_modules) -> None:
    # Read mkinitcpio file
    mkinitcpio_file = open('/etc/mkinitcpio.conf', mode='r')
    mkinitcpio_file_str = mkinitcpio_file.read()
    mkinitcpio_file.close()

    _modules = []
    # Previous modules 
    modules_str = re.search('\nMODULES=(.*)', mkinitcpio_file_str).group()  # 'xxx xx'
    # Tips: '\n' takes 1 byte.
    _modules += modules_str[10:-1].split()
    # New modules
    for new_module in new_modules:
        _modules += new_module.split()

    # Update configuration into initfile_str
    modules_str_new = '\nMODULES=('
    for _module in _modules:
        modules_str_new += (_module + ' ')
    modules_str_new = modules_str_new[:-1] + ')'

    mkinitcpio_file_str = mkinitcpio_file_str.replace(modules_str, modules_str_new)

    # Write into mkinitcpio file
    mkinitcpio_file = open('/etc/mkinitcpio.conf', mode='w')
    mkinitcpio_file.write(mkinitcpio_file_str)
    mkinitcpio_file.close()


class Selection:
    def get_name(self) -> str:
        return ""

    def inst(self) -> None:
        pass
